#!/bin/sh
#
# Make exports from exports.in
#
# Do conditionals first, then strip comments
#

if [ -n "$PCP_TMPFILE_DIR" -a -d "$PCP_TMPFILE_DIR" ]
then
    tmp=`mktemp -d "$PCP_TMPFILE_DIR/pcp-build-mk.exports.XXXXXXXXX"` || exit 1
else
    # assume run during a build and /tmp is a safe bet
    #
    tmp=`mktemp -d "/tmp/pcp-build-mk.exports.XXXXXXXXX"` || exit 1
fi

sts=0
trap "rm -rf $tmp; exit \$sts" 0 1 2 3 15
rm -f $tmp.err exports

if [ ! -f ../../include/pcp.conf ]
then
    echo "mk.exports: Botch: ../../include/pcp.conf missing: configure not run yet?"
    sts=1
    exit
fi
. ../../include/pcp.conf

if [ ! -f ../../include/builddefs ]
then
    echo "mk.exports: Botch: ../../include/builddefs missing: configure not run yet?"
    sts=1
    exit
fi

echo 'BEGIN {' >$tmp.awk
sed -E  -n <../../include/builddefs >>$tmp.awk \
    -e '/^(ENABLE|HAVE)_/{
s/ //g
s/^[^=]*/    builddefs["&/
s/=/"]="/
s/$/"/
p
}'
cat <<End-of-File >>$tmp.awk
}

\$1 == "#if"	{ if (inif) {
		    print "mk.exports: Error: exports.in[" NR "] nested #if" >"$tmp/err"
		    inif = 0
		    exit
		  }
		  inif = NR
		  if (\$2 == "$PCP_PLATFORM") {
		    skip = 0
		  }
		  else if (\$2 !~ /^ENABLE_/ && \$2 !~ /^HAVE_/) {
		    skip = 1
		  }
		  else if (builddefs[\$2] == "") {
		    print "mk.exports: Error: exports.in[" NR "] " \$2 " not defined in ../../include/builddefs" >"$tmp/err"
		    inif = 0
		    exit
		  }
		  else if (builddefs[\$2] != "true" && builddefs[\$2] != "false") {
		    print "mk.exports: Error: exports.in[" NR "] " \$2 " unexpected value (" builddefs[\$2] ") from ../../include/builddefs" >"$tmp/err"
		    inif = 0
		    exit
		  }
		  else if (builddefs[\$2] == "true") {
		    skip = 0
		  }
		  else {
		    skip = 1
		  }
		  next
		}
\$1 == "#else"	{ if (!inif) {
		    print "mk.exports: Error: exports.in[" NR "] missing #if" >"$tmp/err"
		    inif = 0
		    exit
		  }
		  skip = 1 - skip
		  next
		}
\$1 == "#endif"	{ if (!inif) {
		    print "mk.exports: Error: exports.in[" NR "] missing #if" >"$tmp/err"
		    inif = 0
		    exit
		  }
		  inif = 0
		  skip = 0
		  next
		}
skip == 1	{ next }
		{ print }
END		{ if (inif) {
		    print "mk.exports: Error: exports.maser[" inif "] missing #endif" >"$tmp/err"
		    exit
		  }
		}
End-of-File

cat <<End-of-File >exports
# DO NOT EDIT THIS FILE ... CHANGES HERE WILL BE LOST
#
# This file created from exports.in (make changes there!)
# by mk.exports on ${PACKAGE_BUILD_DATE:-$(date -u -d "@$SOURCE_DATE_EPOCH" 2>/dev/null || date -u -r "$SOURCE_DATE_EPOCH" 2>/dev/null || date)}.
#

End-of-File

$PCP_AWK_PROG -f $tmp.awk <exports.in \
| sed -e '/^#/d' >>exports

if [ -f $tmp/err ]
then
    cat $tmp/err
    rm -f exports
    sts=1
else
    chmod a-w exports
fi

exit
